package com.xjc.system.utils;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.xjc.system.properties.AlipayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 徐锦程
 * 时间:2025-03-02 10:48
 */
@Component
public class AlipayUtil {

    @Autowired
    AlipayProperties alipayProperties;

    /**
     * 创建支付宝订单
     * @param tradeNo 商户订单号
     * @param subject 订单标题
     * @param totalAmount 订单总金额
     * @return 支付页面
     */
    public String createOrder(String tradeNo, String subject,String totalAmount){
       try{
           // 初始化SDK
           AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

           // 构造请求参数以调用接口
           AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
           AlipayTradePagePayModel model = new AlipayTradePagePayModel();

           // 设置商户订单号
           model.setOutTradeNo(tradeNo);

           // 设置订单总金额
           model.setTotalAmount(totalAmount);

           // 设置订单标题
           model.setSubject(subject);

           // 设置产品码
           model.setProductCode("FAST_INSTANT_TRADE_PAY");

           // 设置PC扫码支付的方式
           model.setQrPayMode("1");

           // 设置商户自定义二维码宽度
           model.setQrcodeWidth(100L);

           model.setTimeoutExpress("3m");

           // 数据
           request.setBizModel(model);

           // 同步通知地址
           request.setReturnUrl(alipayProperties.getReturnUrl());

           // 异步通知地址
           request.setNotifyUrl(alipayProperties.getNotifyUrl());

           AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");

           return response.getBody();
       }catch (Exception e){
           return null;
       }
    }


    private AlipayConfig getAlipayConfig() {

        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId(alipayProperties.getAppId());
        alipayConfig.setPrivateKey(alipayProperties.getPrivateKey());
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayProperties.getAlipayPublicKey());
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }
}
